// 文件处理相关
import SparkMD5 from 'spark-md5';

// 计算文件的MD5值
export function calculateMD5(file) {
  return new Promise((resolve, reject) => {
    const chunkSize = 5 * 1024 * 1024; // 文件分块后每一块的大小：5*1024*1024 = 1MB 

    const chunks = Math.ceil(file.size / chunkSize); // 文件分块得到的总块数

    let currentChunk = 0;
    const spark = new SparkMD5.ArrayBuffer();
    const fileReader = new FileReader();
    
    fileReader.onload = (e) => {
      spark.append(e.target.result);
      currentChunk++;
      
      if (currentChunk < chunks) { // 如果还有分块
        loadNext();
      } else {
        resolve(spark.end());
      }
    };
    
    fileReader.onerror = (e) => {
      reject(e);
    };
    
    function loadNext() {
      const start = currentChunk * chunkSize;
      const end = Math.min(start + chunkSize, file.size);
      fileReader.readAsArrayBuffer(file.slice(start, end));
    }
    
    loadNext();
  });
}

// 显示文件大小
// 示例：
// console.log(formatFileSize(500));        // 输出: 500 Bytes
// console.log(formatFileSize(1024));       // 输出: 1 KB
// console.log(formatFileSize(1536));       // 输出: 1.5 KB
// console.log(formatFileSize(1048576));    // 输出: 1 MB
// console.log(formatFileSize(5368709120)); // 输出: 5 GB
// console.log(formatFileSize(123456789));  // 输出: 117.74 MB
export function formatFileSize(bytes, decimals = 2) {
    if (bytes === 0) return '0 Bytes';

    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    // 处理小数位数
    const dm = decimals < 0 ? 0 : decimals;
    
    // 使用toFixed和parseFloat来避免小数点后多余的0
    const formattedSize = parseFloat((bytes / Math.pow(k, i)).toFixed(dm));
    
    return `${formattedSize} ${sizes[i]}`;
}